<template>
  <div class="app-container">
    <!-- 左右布局容器 -->
    <div class="flex-container">
      <!-- 左边的卡片列表 -->
      <div class="cardList">
        <div v-for="(item, index) in cardList" :key="index" class="cardView"
             :class="{ 'card-selected': selectedCardId === item.id }" @click="checkProcedure(item.procedureId)">
          <!--				<div>{{ item.code }}</div>-->
          <div>{{ item.procedureName }}</div>
        </div>
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick" type="border-card">
        <el-tab-pane label="报工记录" name="first">
          <el-table v-loading="loading" :data="list1" :stripe="true" :show-overflow-tooltip="true" style="width: 100%">
            <el-table-column label="批次号" align="center" prop="batchNo" width="200"/>
            <el-table-column label="报工号" align="center" prop="reportWorkNo" width="200"/>
            <el-table-column label="工单号" align="center" prop="workOrderNo" width="200"/>
            <el-table-column label="计划编号" align="center" prop="planNo" width="200"/>
            <el-table-column label="工序订单编号" align="center" prop="procedureWorkOrderNo" width="200"/>
            <el-table-column label="报工数量" align="center" prop="reportQuantity" width="200"/>
            <el-table-column label="车间名称" align="center" prop="deptName" width="200"/>
            <el-table-column label="报工产品状态" align="center" prop="reportStatus" width="200"/>
            <!--            0-不合格 1-合格 2-报废-->
            <el-table-column label="产出物料" align="center" prop="planNo" width="200"/>
            <el-table-column label="工序编号" align="center" prop="procedureCode" width="200"/>
            <el-table-column label="工序名称" align="center" prop="procedureName" width="200"/>
            <el-table-column label="设备编号" align="center" prop="deviceCode" width="200"/>
            <el-table-column label="设备名称" align="center" prop="deviceName" width="200"/>
            <el-table-column label="工序名称" align="center" prop="procedureName" width="200"/>
            <el-table-column label="报工数量" align="center" prop="reportQuantity" width="200"/>
            <el-table-column label="报工时间" align="center" prop="createTime" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="投料记录" name="second">
          <el-table v-loading="loading" :data="list2" :stripe="true" :show-overflow-tooltip="true"
          >
            <el-table-column label="任务单号" align="center" prop="workOrderNo"/>
            <el-table-column label="业务类型" align="center" prop="procedureWorkOrderNo"/>
            <el-table-column label="出库库位" align="center" prop="storageName"/>
            <el-table-column label="投料时间" align="center" prop="createTime" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.feedingTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="单据状态" align="center" prop="planNo"/>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="线边库存明细" name="third">
          <el-table v-loading="loading" :data="list3" :stripe="true" :show-overflow-tooltip="true">
            <el-table-column label="批次号" align="center" prop="batchNumber"/>
            <el-table-column label="物料名称" align="center" prop="materialName"/>
            <el-table-column label="物料编号" align="center" prop="materialCode"/>
            <el-table-column label="数量" align="center" prop="quantity"/>
            <el-table-column label="创建时间" align="center" prop="createTime">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="质检记录" name="fourth">
          <el-table v-loading="loading" :data="list4" :stripe="true" :show-overflow-tooltip="true"
          >
            <el-table-column label="质检任务单号" align="center" prop="taskNo"/>
            <el-table-column label="来源类型" align="center" prop="sourceTypeName"/>
            <el-table-column label="批次号" align="center" prop="batchNo"/>
            <el-table-column label="物料编号" align="center" prop="materialCode"/>
            <el-table-column label="物料名称" align="center" prop="materialName"/>
            <el-table-column label="质检方案" align="center" prop="schemeName"/>
            <el-table-column label="任务状态" align="center" prop="status">
              <template v-slot="scope">
                <el-tag v-if="scope.row.status === 0" type="warning">待录入</el-tag>
                <el-tag v-else-if="scope.row.status === 1" type="success">已完成</el-tag>
                <el-tag v-else type="info">未知</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
              <template v-slot="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import * as WorkOrderApi from '@/api/production/workorder';
import * as MaterialApi from '@/api/storage/material';
import * as ReportApi from '@/api/report/traceabilityReportComponent';
import * as InspectionSchemeTaskApi from '@/api/quality/inspectionschemetask';
import {listDept} from "@/api/system/dept";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import Treeselect from "@riophae/vue-treeselect";

export default {
  name: "Second",
  components: {
    Treeselect
  },
  props: {
    batchNo: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      selectedCardId: null,
      cardList: [],
      activeName: 'first',
      batchNoList: [],
      deptList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单列表
      list1: [],
      list2: [],
      list3: [],
      list4: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        workOrderNo: null,
        procedureWorkOrderId: null,
        procedureWorkOrderNo: null,
        planId: null,
        planNo: null,
        deptId: null,
        deptName: null,
        productId: null,
        productName: null,
        productCode: null,
        materialId: null,
        materialNo: null,
        materialName: null,
        procedureId: null,
        procedureCode: null,
        procedureName: null,
        deviceId: null,
        deviceCode: null,
        deviceName: null,
        planBeginTime: [],
        planEndTime: [],
        actualBeginTime: [],
        actualEndTime: [],
        daySendWorkNumber: null,
        status: null,
        createTime: [],
      },
    };
  },
  created() {
    this.getList();
    this.getDeptList();
    // 如果有批次号，则获取工艺路线数据
    if (this.batchNo) {
      this.getProcessRouteByBatch();
    }
  },
  watch: {
    batchNo: {
      handler(newVal) {
        if (newVal) {
          this.getProcessRouteByBatch();
        }
      },
      immediate: true
    }
  },
  methods: {
    /** 获取工艺路线数据 */
    async getProcessRouteByBatch() {
      if (!this.batchNo) return;

      try {
        const res = await ReportApi.getProcessRouteByBatch(this.batchNo);
        // 可以在这里处理返回的数据，比如设置到cardList中
        if (res.data) {
          this.cardList = res.data;
          // 如果cardList长度大于0，则选中第一个并查询相关记录
          if (this.cardList.length > 0) {
            this.selectedCardId = this.cardList[0].id;
            await this.checkProcedure(this.selectedCardId);
          }
        }
      } catch (error) {
        console.error('获取工艺路线数据失败:', error);
        this.$modal.msgError('获取工艺路线数据失败');
      }
    },
    async checkProcedure(procedureId) {
      if (!procedureId || !this.batchNo) return;

      console.log('查询工序相关记录，工序ID:', procedureId, '批次号:', this.batchNo);

      const param = {
        batchNo: this.batchNo,
        procedureId: procedureId
      };

      try {
        // 并行调用四个接口
        const [reportRes, feedingRes, storageRes, qualityRes] = await Promise.all([
          ReportApi.getReportByBatch(param),      // 报工记录
          ReportApi.getFeedingByBatch(param),      // 投料记录
          ReportApi.getStorageMaterialByBatch(param), // 线边库存明细
          ReportApi.getQualityTaskByBatch(param)   // 质检记录
        ]);

        // 设置报工记录到list1
        this.list1 = reportRes.data || [];
        console.log('报工记录数据:', this.list1);

        // 设置投料记录到list2
        this.list2 = feedingRes.data || [];
        console.log('投料记录数据:', this.list2);

        // 设置线边库存明细到list3
        this.list3 = storageRes.data || [];
        console.log('线边库存明细数据:', this.list3);

        // 设置质检记录到list4
        this.list4 = qualityRes.data || [];
        console.log('质检记录数据:', this.list4);

      } catch (error) {
        console.error('获取工序相关记录失败:', error);
        this.$modal.msgError('获取工序相关记录失败');
      }
    },
    handleClick(e) {
      console.log(e._props.label, 'czq')
    },
    async getDeptList() {
      const res = await MaterialApi.getMaterialPage({pageNo: 1, pageSize: 50});
      this.batchNoList = res.data.list;
    },

    /** 部门节点格式化 */
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    toDetail(id) {
      this.$router.push({
        path: '/production/detail',
        query: {id: id}
      });
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await WorkOrderApi.getWorkOrderPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除工单编号为"' + id + '"的数据项?')
      try {
        await WorkOrderApi.deleteWorkOrder(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除工单 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await WorkOrderApi.deleteWorkOrderList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有工单数据项?');
      try {
        this.exportLoading = true;
        const data = await WorkOrderApi.exportWorkOrderExcel(this.queryParams);
        this.$download.excel(data, '工单.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    }
  }
};
</script>
<style scoped>
.flex-container {
  display: flex;
  gap: 20px;
  width: 100%;
  min-height: 600px;
}

.cardList {
  width: 200px;
  min-width: 200px;
  max-width: 200px;
  flex-shrink: 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 10px;
  overflow-y: auto;
  height: fit-content;
  max-height: 600px;
}

.el-tabs {
  flex: 1;
  min-width: 0; /* 防止flex子项溢出 */
}

.el-tabs ::v-deep .el-tabs__content {
  overflow-x: auto;
  min-height: 500px;
}

.el-table {
  min-width: 100%;
}

.cardView {
  padding: 15px;
  margin-bottom: 10px;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  text-align: center;
  transition: all 0.3s;
  border: 1px solid #dcdfe6;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.cardView:hover {
  border-color: #409eff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.card-selected {
  border-color: #409eff !important;
  background-color: #ecf5ff !important;
  box-shadow: 0 0 0 1px #409eff;
}
</style>
